package com.kmxd.ams.app.arrange.command;

import static com.kmxd.ams.core.common.constant.ArchConst.DICT_RETENTIONPERIOD;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.kmxd.ams.client.system.ISysDictSvc;
import com.kmxd.ams.core.common.bo.DictModel;
import com.kmxd.ams.core.util.SecurityUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/** 保管到期获取 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RetentionCmd {
  private final ISysDictSvc sysDictSvc;

  public Date getExpireYear(Integer year, String retentionPeriod, Date docTime) {
    try {
      return getExpireYear(year, 0, 0, retentionPeriod, docTime);
    } catch (Exception e) {
      e.printStackTrace();
      log.debug("计算到期时间异常：", e.getMessage());
    }
    return null;
  }

  /**
   * 获取到期时间
   *
   * @param year 年度
   * @param retentionPeriod 保管期限
   * @param docTime 成文日期或案卷开始日期
   * @return
   */
  public Date getExpireYear(Integer year, int month, int day, String retentionPeriod, Date docTime) {
    Date data = null;
    try {
      List<DictModel<String>> dictModels =
          sysDictSvc.listDictModel(
              DICT_RETENTIONPERIOD, "general", year, null, null, SecurityUtil.getCropId());
      DictModel dictModel =
          dictModels.stream()
              .filter(x -> ObjectUtil.equal(x.getValue(), retentionPeriod) ||ObjectUtil.equal(x.getLabel(), retentionPeriod))
              .findFirst()
              .orElse(null);
      if (ObjectUtil.isEmpty(dictModel)) {
        dictModel =
            dictModels.stream()
                .filter(x -> ObjectUtil.equal(x.getLabel(), retentionPeriod))
                .findFirst()
                .orElse(null);
      }
      if (ObjectUtil.isNotEmpty(dictModel) && ObjectUtil.isNotEmpty(dictModel.getExt1())) {
        int yearAdd =
            NumberUtil.isNumber(dictModel.getExt1()) ? Integer.parseInt(dictModel.getExt1()) : 0;
        data = getNewDate(docTime, yearAdd, month, day);
      }
    } catch (Exception e) {
      log.debug("计算到期时间异常:{}", e.getMessage());
    }
    return data;
  }

  public static Date getNewDate(Date date, int year, int month, int day) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    calendar.add(Calendar.YEAR, year);
    calendar.add(Calendar.MONTH, month);
    calendar.add(Calendar.DATE, day);
    return calendar.getTime();
  }
}
